<?php

namespace App\Exceptions;

use App\Common\Helper\ApiReturnHelper;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Exceptions\ThrottleRequestsException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * The list of the inputs that are never flashed to the session on validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     */
    public function register(): void
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }

    public function render($request, Throwable $e)
    {
        if ($e instanceof CommonException) { //通用异常
            return ApiReturnHelper::newInstance()->commonResponse($e->getCode(), $e->getMessage());
        } else if ($e instanceof NotFoundHttpException) { //路由不存在异常
            return ApiReturnHelper::newInstance()->commonResponse(404, '路由不存在');
        } else if ($e instanceof UnauthorizedHttpException) { //授权问题
            return ApiReturnHelper::newInstance()->commonResponse(401, '用户未登录');
        } else if ($e instanceof ThrottleRequestsException) { //调用频率限制
            return ApiReturnHelper::newInstance()->commonResponse(429, '已触发接口调用频率限制');
        }

        return ApiReturnHelper::newInstance()->commonResponse(500, join(':', [$e->getMessage(), $e->getFile(), $e->getLine()]));
//        return parent::render($request, $e); // TODO: Change the autogenerated stub
    }
}
